package com.lyf.network.practice.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * @AUTHOR LYF
 * @DATE 2022/5/24
 * @VERSION 1.0
 * @DESC
 */
public class NettyClient {
    public static void main(String[] args) throws InterruptedException, IOException {
        Channel channel = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                    }
                }).connect(new InetSocketAddress(8081))
                .sync()
                .channel();

        while (true){

            String monitorFile = "E:\\JavaProjects\\LearnProjects\\learn-practice\\java-base\\src\\main\\resources\\files\\nettyFile.txt";
            FileInputStream fileInputStream = new FileInputStream(monitorFile);
            byte[] bytes=new byte[12];
            fileInputStream.read(bytes);
            String str =new String(bytes);
            System.out.println("检查为:"+str);
            TimeUnit.SECONDS.sleep(1);//心跳
            // 写给 server
            channel.writeAndFlush(str);
        }

    }
}
